package com.yinNuo.collectWool.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: yinNuo
 * create at: 2021/12/1 下午9:20
 * @description: HttpHeaders工具类
 */
@Component
public class HttpUtils {

    @Autowired
    private RestTemplate restTemplate;

    public static String getContextHttpUri(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    /**
     * 统一设置AndroidHttpHeaders
     *
     * @return
     */
    public void setAndroidHttpHeaders(HttpHeaders headers) {
        //设置Header 虽然不设置也可以获取到数据 但防止系统更新后台解析header，此处设置一下以防万一
        headers.set("Content-Type", "application/x-www-form-urlencoded");
        headers.set("User-Agent", "Mozilla/5.0 (Linux; Android 12; Redmi K40 Pro Build/QKQ1.190825.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.138 Mobile Safari/537.36 uni-app Html5Plus/1.0 (Immersed/34.909092)");
        headers.set("Host", "api.st615.com");
        headers.set("Connection", "keep-alive");
        //headers.set("Accept-Encoding", "gzip");
    }

    /**
     * 封装get请求 获取body
     *
     * @param url       请求路径
     * @param headers   请求头设置
     * @param paramsMap 请求携带的参数 (参数在url中则直接拼接到url上，若在请求体中则存入map中)
     * @return
     */
    public String getMethod(String url, HttpHeaders headers, Map<String, Object> paramsMap) {
        setAndroidHttpHeaders(headers);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramsMap, headers);
        return restTemplate.getForEntity(url, String.class, httpEntity).getBody();
    }

    /**
     * 封装post请求
     *
     * @param url       请求路径
     * @param headers   请求头设置
     * @param paramsMap 请求携带的参数
     * @return result
     */
    public String postMethod(String url, HttpHeaders headers, MultiValueMap<String, String> paramsMap) {
        setAndroidHttpHeaders(headers);
        HttpEntity<MultiValueMap<String, String>> mapHttpEntity = new HttpEntity<>(paramsMap, headers);
        return restTemplate.postForEntity(url, mapHttpEntity, String.class).getBody();
    }
}
